package org.dydl.common.config;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

public class AccessDeniedServletRequestHandler extends AccessDeniedHandlerImpl {
    // Inject this into your class.
    private HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
            AccessDeniedException accessDeniedException) throws IOException, ServletException {
        if (!response.isCommitted()) {
            SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
            if (null != savedRequest) {
            	requestCache.removeRequest(request, response);
            }
        	requestCache.saveRequest(request, response);
        	super.handle(request, response, accessDeniedException);
        }
    }

}
